/**
 * Created by lbs on 2017/3/15.
 */

function getNowTime(){
    var str = '',
        year,
        month,
        day,
        hours,
        minutes,
        seconds,
        millSeconds,
        date = new Date();
        year = date.getFullYear();
        month = date.getMonth()+1;
        day = date.getDate();
        hours = date.getHours();
        minutes = date.getMinutes();
        seconds = date.getSeconds();
        millSeconds = date.getMilliseconds();
        month = month<10?'0'+month:month;
        day = day<10?'0'+day:day;
        hours = hours<10?'0'+hours:hours;
        minutes = minutes<10?'0'+minutes:minutes;
        seconds = seconds<10?'0'+seconds:seconds;
        millSeconds = millSeconds<10?'0'+millSeconds:millSeconds;
        str = ''+year+month+day+hours+minutes+seconds+millSeconds;
        return str;
}


// 配置上传
function uploadInit() {
    var editor = this;
    var count = 0;
    var btnId = editor.customUploadBtnId;
    var containerId = editor.customUploadContainerId;
    var accessid = 'LTAIKc4SmxqXnWjb';
    var accesskey = 'n2mZHgH4SfHCaTOips4iuR2h4NOsjo';
    var host = 'https://ddup-img1.oss-cn-hangzhou.aliyuncs.com';

    var policyText = {
        "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
        "conditions": [
            ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
        ]
    };
    var policyBase64 = Base64.encode(JSON.stringify(policyText))
    var message = policyBase64
    var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, {asBytes: true});
    var signature = Crypto.util.bytesToBase64(bytes);
    var date = Date.parse(new Date());
    //实例化一个上传对象
    var uploader = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        browse_button: btnId,
        url: host,
        container: containerId,
        flash_swf_url: 'lib/plupload/plupload/Moxie.swf',
        sliverlight_xap_url: 'lib/plupload/plupload/Moxie.xap',
        filters: {
            mime_types: [
                //只允许上传图片文件 （注意，extensions中，逗号后面不要加空格）
                {title: "图片文件", extensions: "jpg,gif,png,bmp"}
            ]
        },
        multipart_params: {
            'Filename': '${filename}',
            //'key': date + '${filename}',
            'key': getNowTime(),
            'policy': policyBase64,
            'OSSAccessKeyId': accessid,
            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
            'signature': signature,
        }
    });

//存储所有图片的url地址
    var urls = [];

//            初始化
    uploader.init();

    //绑定文件添加到队列的事件
    uploader.bind('FilesAdded', function (uploader, files) {
        //显示添加进来的文件名
        var fileName = [];
        var name = '';
        $.each(files, function (key, value) {
            fileName.push(value.name);
            // 文件添加之后，开始执行上传
            date =getNowTime();
            uploader.settings.multipart_params.key = date;
            uploader.start();
            name= date;
            urls.push(host + "/" + name + '?tag=' + Math.random())
        });
    });

//            单个文件上传之后
    uploader.bind('FileUploaded', function (uploader, file, responseObject) {

    });

//            全部文件上传时候
    uploader.bind('UploadComplete', function (uploader, files) {
        try {
            $.each(urls, function (key, value) {
                editor.command(null, 'insertHtml', '<img src="' + value + '" "/>');
            });
        } catch (ex) {
        } finally {
            urls = [];
            editor.hideUploadProgress();
        }
    });

//             上传进度条
    uploader.bind('UploadProgress', function (uploader, file) {
        // 显示进度条
        editor.showUploadProgress(file.percent);
    });
}

// 创建编辑器
var editor = new wangEditor('editor-trigger');
editor.config.menus = [
    'source',
    '|',
    'bold',
    'underline',
    'forecolor',
    'fontsize',
    '|',
    'head',
    'alignleft',
    'alignright',
    'aligncenter',
    '|',
    'link',
    'unlink',
    'img',
    '|',
    'undo',
    'redo',
    'fullscreen'
]
editor.config.colors = {
    '#000000': '黑',
    '#0c0c0c': '黑1',
    '#262626': '黑2',
    '#3f3f3f': '黑3',
    '#595959': '黑4',
    '#7f7f7f': '黑5',
    '#c0504d': '暗红',
    '#632423': '暗红1',
    '#953734': '暗红2',
    '#d99694': '暗红3',
    '#e5b9b7': '暗红4',
    '#f2dcdb': '暗红5',
    '#f79646': '橘黄',
    '#974806': '橘黄1',
    '#e36c09': '橘黄2',
    '#fac08f': '橘黄3',
    '#fbd5b5': '橘黄4',
    '#fdeada': '橘黄5',
    '#4bacc6': '蓝',
    '#dbeef3': '蓝1',
    '#b7dde8': '蓝2',
    '#92cddc': '蓝3',
    '#31859b': '蓝4',
    '#205867': '蓝5',
    '#c00000': '深红',
    '#ff0000': '红',
    '#ffc000': '深黄',
    '#ffff00': '黄',
    '#92d050': '绿',
    '#00b050': '深绿',
    '#00b0f0': '蓝',
    '#0070c0': '深蓝',
    '#002060': '暗紫',
    '#7030a0': '紫'
};

editor.config.fontsizes = {
    // 格式：'value': 'title'
    1: '14px',
    2: '13px',
    3: '16px',
    4: '19px',
    5: '22px',
    6: '25px',
    7: '28px'
};


editor.config.customUpload = true;  // 配置自定义上传
editor.config.customUploadInit = uploadInit;  // 配置上传事件
editor.create();
$('#editor-trigger').empty();

